package com.mazaiting.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

/**
 * Gate 配置
 */
@Slf4j
@Configuration
public class FilterConfig {

    /**
     * 全局调用耗时过滤器
     *
     * @return 全局过滤器
     */
    @Bean
    @Order(-100) // 顺序
    public GlobalFilter elapsedGlobalFilter() {
        return (exchange, chain) -> {
            //调用请求之前统计时间
            Long startTime = System.currentTimeMillis();
            return chain.filter(exchange).then().then(Mono.fromRunnable(() -> {
                //调用请求之后统计时间
                Long endTime = System.currentTimeMillis();
                log.info(
                        exchange.getRequest().getURI().getRawPath() + ", cost time : " + (endTime - startTime) + "ms");
            }));
        };
    }

    /**
     * 全局日志过滤器
     *
     * @return 全局过滤器
     */
    @Bean
    @Order(-1)
    public GlobalFilter logGlobalFilter() {
        return (exchange, chain) -> {
            // 请求路径
            String rawPath = exchange.getRequest().getURI().getRawPath();
            log.info("=============== {} start: {} ===============", rawPath, LocalDateTime.now());
            return chain.filter(exchange).then().then(Mono.fromRunnable(() -> {
                log.info("=============== {} end: {} ===============", rawPath, LocalDateTime.now());
            }));

        };
    }

}